package com.android.myapplication.view;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

import com.android.myapplication.R;
import com.android.myapplication.main.BaseActvity;
import com.android.myapplication.main.Utile;
import com.android.myapplication.view.adapter.StudentBean;
import com.android.myapplication.view.database.ClassBean;
import com.android.myapplication.view.database.MyCursorAdapter;
import com.android.myapplication.view.database.MySqlite;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import androidx.appcompat.app.AlertDialog;

public class DatabaseActivty extends BaseActvity {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };

    Button mBtnShared;
    TextView mTxtView;

    Runnable mWaitPermissionsRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database);
        init();
        mBtnShared = findViewById(R.id.btn_shared);
        mTxtView = findViewById(R.id.txt_value);
        mBtnShared.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createDailog(getShared(), new InputDailogCallback() {
                    @Override
                    public void onCallback(String text) {
                        saveShared(text);
                        mBtnShared.setText(getShared());
                    }
                }, 1);
            }
        });
        mBtnShared.setText(getShared());
        mTxtView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createDailog(readFile(mTxtView), new InputDailogCallback() {
                    @Override
                    public void onCallback(String text) {
                        saveFile(text);
                        readFile(mTxtView);

                    }
                }, 1);
            }
        });
        readFile(mTxtView);

        final ListView listView = findViewById(R.id.list);
        MySqlite mySqlite = new MySqlite(this);
        listView.setAdapter(new CursorAdapter(this, mySqlite.getReadableDatabase().query("class", null, null, null, null, null, null, null)) {
            @Override
            public View newView(Context context, Cursor cursor, ViewGroup parent) {
                View view =  LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, null);
                return view;
            }

            @Override
            public void bindView(View view, Context context, Cursor cursor) {
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String year = cursor.getString(cursor.getColumnIndex("year"));
                ((TextView)view).setText("name : " + name + " year = " + year);
            }
        });

//        listView.setAdapter(new MyCursorAdapter(this, mySqlite.getReadableDatabase().query("class", null, null, null,null,null,null,null)));

        findViewById(R.id.btn_add_student).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new AlertDialog.Builder(DatabaseActivty.this).setTitle("添加班级")
                        .setIcon(android.R.drawable.sym_def_app_icon)
                        .setView(R.layout.dialog_edit_class)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Dialog dialog = (Dialog) dialogInterface;

                                String className = ((EditText)dialog.findViewById(R.id.ed_class)).getText().toString();
                                String year = ((EditText)dialog.findViewById(R.id.ed_year)).getText().toString();
                                ClassBean classBean = new ClassBean();
                                classBean.setName(className);
                                classBean.setYear(year);
                                MySqlite mySqlite = new MySqlite(DatabaseActivty.this);
                                mySqlite.saveClass(classBean);
                                ((CursorAdapter)listView.getAdapter()).changeCursor(mySqlite.getReadableDatabase().query("class", null, null, null,null,null,null,null));
                                mySqlite.close();
                                dialogInterface.dismiss();
                            }
                        }).setNegativeButton("取消",null).show();
            }
        });
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_EXTERNAL_STORAGE && resultCode == RESULT_OK){
            if (mWaitPermissionsRunnable != null){
                mWaitPermissionsRunnable.run();
            }
        }
    }

    private void saveShared(String text){
      SharedPreferences.Editor editor = getSharedPreferences("mydata", Context.MODE_PRIVATE).edit();
      editor.putString("my" , text);
      editor.commit();
    }

    private String getShared(){
        SharedPreferences sharedPreferences = getSharedPreferences("mydata", Context.MODE_PRIVATE);
        return sharedPreferences.getString("my", "设置按钮文字");
    }

    private void saveFile(final String text){
        if (!Utile.verifyStoragePermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE)){
            mWaitPermissionsRunnable = new Runnable() {
                @Override
                public void run() {
                    saveFile(text);
                }
            };
        }
        File dir = new File(getFilesDir().getPath());
        if (!dir.exists()){
            dir.mkdirs();
        }
        File file = new File(dir, "test.txt");
        BufferedOutputStream outputStream = null;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(file));
            outputStream.write(text.getBytes("utf-8"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String readFile(final TextView textView){
        if (!Utile.verifyStoragePermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE)){
            mWaitPermissionsRunnable = new Runnable() {
                @Override
                public void run() {
                    readFile(textView);
                }
            };
        }
        File file = new File(getFilesDir().getPath(), "test.txt");
        if (!file.exists()){
            textView.setText("文件不存在");
            return "文件不存在";
        }
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            StringBuffer buffer = new StringBuffer();
            String str;
            while ((str = bufferedReader.readLine()) != null){
                buffer.append(str);
            }
            textView.setText(buffer.toString());
            return buffer.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        textView.setText("读取文件异常");
        return "读取文件异常";

    }

    private void createDailog(String text, final InputDailogCallback listener, int lines){
        final EditText et = new EditText(DatabaseActivty.this);
        et.setText(text);
        et.setLines(lines);
        new AlertDialog.Builder(DatabaseActivty.this).setTitle("请需要存入内容")
                .setIcon(android.R.drawable.sym_def_app_icon)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        listener.onCallback(et.getText().toString());
                        dialogInterface.dismiss();
                    }
                }).setNegativeButton("取消",null).show();
    }

    interface InputDailogCallback{
        public void onCallback(String text);
    }
}